package Chapter10_InnerClass;

/**
 * Date: 2019/2/19
 * Time: 10:06
 * User: Driss.
 *
 * 10.2 链接到外部类
 *
 * 使用了“迭代器”设计模式
 */

interface Selector{
    boolean end();
    Object current();
    void next();
}

public class Sequence {


    private Object[] items;
    private int next = 0;
    public Sequence(int size){
        items = new Object[size];
    }

    public void add(Object x){
        if(next < items.length){
            items[next++] = x;
        }
    }

    //内部类
    private class SequenceSelector implements  Selector{
        private int i = 0;
        public boolean end() { return i == items.length;} //内部类可以直接访问外部类的私有域
        public Object current() { return items[i]; }
        public void next() { if(i < items.length) i++; }
    }

    //返回一个内部类对象
    public Selector selector(){return new SequenceSelector();}

    public static void main(String[] args) {
        Sequence sequence = new Sequence(10);
        for (int i = 0; i < 10; i++) {
            sequence.add(Integer.toString(i));
        }
        Selector selector = sequence.selector();
        while(!selector.end()){
            System.out.print(selector.current() + " ");
            selector.next();
        }
    }
}
